package cn.stylefeng.roses.kernel.pay.modular.factory;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.pay.api.enums.OrderStateEnum;
import cn.stylefeng.roses.kernel.pay.modular.entity.Goods;
import cn.stylefeng.roses.kernel.pay.modular.entity.Order;
import cn.stylefeng.roses.kernel.pay.modular.pojo.GoodsRequest;
import cn.stylefeng.roses.kernel.pay.modular.service.GoodsService;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 订单工厂
 *
 * @author fengshuonan
 * @date 2021/6/23 23:20
 */
public class OrderFactory {

    /**
     * 创建订单对象
     *
     * @author fengshuonan
     * @date 2021/6/23 23:20
     */
    public static Order createOrder(Goods goods, Date expireDate) {
        Order order = new Order();

        // 生成订单号
        String orderNumber = DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomString(10);
        order.setOrderNumber(orderNumber);

        // 过期时间
        order.setExpirationTime(expireDate);

        // 订单的购买人
        Long userId = LoginContext.me().getLoginUser().getUserId();
        order.setCustomerId(userId);

        // 商品id
        order.setGoodsId(goods.getGoodsId());

        // 商品名称
        order.setGoodsName(goods.getGoodsName());

        // 商品总价
        order.setTotalPrice(goods.getPrice());

        // 支付价格
        order.setPayPrice(goods.getPrice());

        // 状态
        order.setState(OrderStateEnum.WAIT_PAY.getCode());

        return order;
    }

    /**
     * 创建订单对象
     *
     * @author fengshuonan
     * @date 2021/6/23 23:20
     */
    public static Order createEleAdminOrder(Long userId,Long goodsId) {

        // 查询商品是否存在
        GoodsRequest goodsRequest = new GoodsRequest();
        goodsRequest.setGoodsId(goodsId);
        GoodsService goodsService = SpringUtil.getBean(GoodsService.class);
        Goods goods = goodsService.detail(goodsRequest);

        // 生成订单号
        Order order = new Order();
        String orderNumber = DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomString(10);
        order.setOrderNumber(orderNumber);

        // 过期时间
        order.setExpirationTime(null);

        // 订单的购买人
        order.setCustomerId(userId);

        // 商品id
        order.setGoodsId(goods.getGoodsId());

        // 商品名称
        order.setGoodsName(goods.getGoodsName());

        // 商品总价
        order.setTotalPrice(goods.getPrice());

        // 支付价格
        order.setPayPrice(new BigDecimal(0));

        // 支付时间为创建时间
        order.setPayTime(new Date());

        // 状态
        order.setState(OrderStateEnum.COMPLETE.getCode());

        return order;
    }

}
